package com.tiger.chat.config;


import com.tiger.chat.provider.OpenAIProvider;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.atomic.AtomicInteger;

@Component
@Slf4j
@ServerEndpoint(value = "/websocket/{type}/{pwd}")
public class WebSocketServer {
    private static final AtomicInteger COUNT = new AtomicInteger(0);
    private static  ChatProperty CHAT_PROPERTY;
    private static OpenAIProvider OPEN_AI_PROVIDER;
    private Session session;
    private String type;

    private String password;
    public static void initChatProperty(ChatProperty chatProperty){
        CHAT_PROPERTY = chatProperty;
    }
    public static void initAI(OpenAIProvider openAIProvider){
        OPEN_AI_PROVIDER = openAIProvider;
    }
    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session,@PathParam("type") String type, @PathParam("pwd") String pwd) {
        log.info("有连接加入.当前人数：{}",COUNT.incrementAndGet());
        this.session = session;
        this.type = type;
        sendMessage("欢迎体验AI聊天,made by 胖虎,晓月 Email:fengkuangdejava@outlook.com,luxiaoyue@qq.com");
        this.password = pwd;
    }


    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        log.info("连接关闭！当前在线人数为{}",COUNT.decrementAndGet());
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        log.info("来自客户端用户：{} 消息:{}",session.getId(), message);
        String msg = "openAI暂时关闭,假装这是openAI的回复";
        if(CHAT_PROPERTY.isEnable()) {
            if(password.equals(CHAT_PROPERTY.getPwd())) {
                try {
                    if ("code".equals(type)) {
                        msg = OPEN_AI_PROVIDER.sendCodeMsg(message);
                    } else {
                        msg = OPEN_AI_PROVIDER.sendChatMsg(message);
                    }
                }catch (Exception e){
                    msg = "chatGpt调用失败,请联系管理员检查chatGpt是否配置正确,是否余额充足";
                }
            }else{
                msg="因为ChatGPT调用收费,所以设置了密码,当前用户输入密码不对,无法智能回复,请修改,抱歉!";
            }
        }
        sendMessage(msg);
    }

    /**
     * 发生错误时调用
     *
     * @OnError
     */
    @OnError
    public void onError(Session session, Throwable error) {
        log.error("用户错误:" + session==null?"":session.getId() + ",原因:" + error==null?"":error.getMessage());
        error.printStackTrace();
    }

    /**
     * 向客户端发送消息
     */
    public void sendMessage(String message){
        log.info("下发消息：{}",message);
        try {
            this.session.getBasicRemote().sendText(message);
        }catch (IOException e){
            log.error("下发消息失败:",e);
        }
    }
}
